<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" :hidden-horizontal="false" class="form-dialog" width="60%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="formLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             class="data-form"
             label-width="140px"
             status-icon>
      <template v-if="configType === 0">
        <el-form-item label="配置参数名称：" prop="name">
          <el-input v-model="formData.name" :readonly="readonly" placeholder="参数名称"/>
        </el-form-item>

        <el-form-item label="配置参数键名：" prop="config_key">
          <el-input v-model="formData.config_key" :readonly="readonly" placeholder="参数键名"/>
        </el-form-item>

        <el-form-item label="配置参数键值：" prop="config_value">
          <el-input v-model="formData.config_value"
                    :autosize="{ minRows: 2, maxRows: 10}"
                    :readonly="readonly" placeholder="参数键值" type="textarea"/>
          <json-viewer v-if="isJsonData(formData.config_value)" :expand-depth="4" :value="JSON.parse(formData.config_value)"/>
        </el-form-item>
      </template>

      <!-- 后台管理登录配置 -->
      <template v-if="configType === 1">
        <SysLoginConfig :captcha-config="configValue1" :config-type="configType" :config-value="configValue" :readonly="readonly"/>
      </template>

      <!-- Api服务配置 -->
      <template v-if="configType === 2">
        <ServerConfig :config-type="configType" :config-value="configValue" :readonly="readonly"/>
      </template>

      <!-- 用户规则配置 -->
      <template v-if="configType === 3">
        <UserRuleConfig :config-type="configType" :config-value="configValue" :name-prefix-list="dynamicTags" :readonly="readonly" v-model:withdraw-share-types="configList"/>
      </template>

      <!-- 验证码规则配置 -->
      <template v-if="configType === 4">
        <CaptchaRuleConfig :config-type="configType" :config-value="configValue" :platform-list="configList" :readonly="readonly"/>
      </template>

      <!-- 线上规则配置 -->
      <template v-if="configType === 10">
        <ShopRuleConfig ref="shopRuleConfig" :config-type="configType" :config-value="configValue" :not-shipped-list="configList" :readonly="readonly"/>
      </template>

      <!-- 资金规则配置 -->
      <template v-if="configType === 11">
        <CapitalRuleConfig :config-type="configType" :config-value="configValue" :readonly="readonly"/>
      </template>

      <!-- 门店规则配置 -->
      <template v-if="configType === 12">
        <StoreRuleConfig ref="storeRuleConfig" :config-type="configType" :config-value="configValue" :readonly="readonly" :manager-list="configList"/>
      </template>

      <!-- 阿里云密匙配置 -->
      <template v-if="configType === 20">
        <AliyunCsConfig :config-type="configType" :config-value="configValue" :readonly="readonly"/>
      </template>

      <!-- 微信配置 -->
      <template v-if="configType === 21">
        <WechatConfig :config-type="configType" :config-value="configValue" :readonly="readonly"/>
      </template>

      <!-- 支付配置 -->
      <template v-if="configType === 30 || configType === 31 || configType === 32 || configType === 33">
        <PaymentConfig :config-type="configType" :config-value="configValue" :product-configs="configList" :readonly="readonly"/>
      </template>

      <!-- 其他信息 -->
      <template v-if="configType > 0">
        <el-form-item label="配置参数名称：" prop="name">
          <el-input v-model="formData.name" :readonly="readonly" placeholder="参数名称"/>
        </el-form-item>
      </template>

      <el-form-item label="配置备注信息：">
        <el-input v-model="formData.remark" :readonly="readonly" placeholder="备注信息"/>
      </el-form-item>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['sys:config:create', 'sys:config:update']" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, nextTick, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { sysConfigInfo, sysConfigSaveOrUpdate } from '@/api/api-sys.ts';
import { DynamicItem } from '@/components/dynamic-tags/src/types.ts';
import JsonViewer from 'vue-json-viewer';
import { isJsonData } from '@/utils/is.ts';
import useDialog from '@/hooks/use-dialog.ts';
import { SvgIcon } from '@/components/icon';
import { EcDialog } from '@/components/dialog';
import SysLoginConfig from './components/SysLoginConfig.vue';
import ServerConfig from './components/ServerConfig.vue';
import UserRuleConfig from './components/UserRuleConfig.vue';
import CaptchaRuleConfig from './components/CaptchaRuleConfig.vue';
import AliyunCsConfig from './components/AliyunCsConfig.vue';
import ShopRuleConfig from './components/ShopRuleConfig.vue';
import PaymentConfig from './components/PaymentConfig.vue';
import CapitalRuleConfig from './components/CapitalRuleConfig.vue';
import WechatConfig from './components/WechatConfig.vue';
import StoreRuleConfig from './components/StoreRuleConfig.vue'

defineOptions({name: 'SysMenuForm'})

const formRef = ref<FormInstance>();
const formLoading = ref(false);// 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

// 默认表单数据
let defaultForm = {
  id: 0,
  name: '',
  config_key: '',
  config_value: '',
  remark: '',
  enabled: true
};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{required: true, message: '参数名称不能为空', trigger: 'blur'}],
  config_key: [{required: true, message: '参数键名不能为空', trigger: 'blur'}],
  config_value: [{required: true, message: '参数键值不能为空', trigger: 'blur'}],
});

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || !formData.value.id || formData.value.id <= 0;
});

const configType = ref(0);
const configValue = ref({});
const configValue1 = ref({});
const configValue2 = ref({});
const configValue3 = ref({});

const dynamicTags = ref<DynamicItem[]>([]);
const configList = ref<any[]>([]);
const configList1 = ref<any[]>([]);
const configList2 = ref<any[]>([]);
const configList3 = ref<any[]>([]);
const configList4 = ref<any[]>([]);

const shopRuleConfig = ref<any>();
const storeRuleConfig = ref<any>();

/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '配置文件';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();

  // 加载信息
  if (id) {
    formLoading.value = true
    try {
      // 加载数据
      const {data} = await sysConfigInfo(id)
      formData.value = data;
      dialogTitle.value = data.name;

      let configKey = data.config_key;
      if (configKey === 'SYS_LOGIN_CONFIG_KEY') {
        configType.value = 1;
      } else if (configKey === 'SERVER_CONFIG_KEY') {
        configType.value = 2;
      } else if (configKey === 'USER_RULE_CONFIG_KEY') {
        configType.value = 3
      } else if (configKey === 'CAPTCHA_RULE_CONFIG_KEY') {
        configType.value = 4
      } else if (configKey === 'SHOP_RULE_CONFIG_KEY') {
        configType.value = 10
      } else if (configKey === 'CAPITAL_RULE_CONFIG_KEY') {
        configType.value = 11
      } else if (configKey === 'STORE_RULE_CONFIG_KEY') {
        configType.value = 12
      }

      if (configKey === 'ALIYUN_CS_RULE_KEY') { // 阿里云配置
        configType.value = 20
      } else if (configKey === 'WECHAT_CONFIG_KEY') { // 微信配置
        configType.value = 21
      }

      if (configKey === 'PAYMENT_ALIPAY_CONFIG_KEY') { // 支付宝支付配置
        configType.value = 30
      } else if (configKey === 'PAYMENT_WECHAT_CONFIG_KEY') { // 微信支付配置
        configType.value = 31
      } else if (configKey === 'PAYMENT_HEEPAY_CONFIG_KEY') { // 汇付宝支付配置
        configType.value = 32
      } else if (configKey === 'PAYMENT_HUAWEIGU_CONFIG_KEY') { // 华微谷支付配置
        configType.value = 33
      }

      if (configType.value > 0) {
        // 解析配置值
        configValue.value = JSON.parse(data.config_value);

        // 按类型区分配置
        if (configType.value === 1) {
          configValue1.value = configValue.value['captchaConfig'] || {}
        } else if (configType.value === 3) { // 用户配置
          initDynamicTags(configValue.value['namePrefixList'] || [])
          initConfigList(configValue.value['withdrawShareTypes'] || [])
        } else if (configType.value === 4) { // 验证码规则配置
          initConfigList(configValue.value['platformList'] || [])
        } else if (configType.value === 10) { // 商城规则配置
          initConfigList(configValue.value['notShippedList'] || [])
          await nextTick(() => shopRuleConfig.value?.handleResetData());
        } else if (configType.value === 12) { // 门店规则配置
          initConfigList(configValue.value['globalManagers'] || [])
          await nextTick(() => storeRuleConfig.value?.handleResetData());
        } else if (configType.value === 32) { // 汇付宝支付配置
          initConfigList(configValue.value['productConfigs'] || [])
        }
      }
    } catch (err) {
      console.log(err)
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open})

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  if (readonly.value) return
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }

    // 对数据进行处理
    if (configType.value > 0) {
      if (configType.value === 1) { // 后台管理验证码配置
        configValue.value['captchaConfig'] = configValue1.value
      } else if (configType.value === 3) { // 用户配置
        configValue.value['namePrefixList'] = [];
        dynamicTags.value.forEach(item => configValue.value['namePrefixList'].push(item.item))

        let key = 'withdrawShareTypes';
        configValue.value[key] = [];
        configList.value.forEach(item => configValue.value[key].push(item))
      } else if (configType.value === 4) { // 验证码规则配置
        let key = 'platformList';
        configValue.value[key] = [];
        configList.value.forEach(item => configValue.value[key].push(item))
      } else if (configType.value === 10) { // 商城规则配置
        let key = 'notShippedList';
        configValue.value[key] = [];
        configList.value.forEach(item => configValue.value[key].push(item))
      } else if (configType.value === 12) { // 门店规则配置
        let key = 'globalManagers';
        configValue.value[key] = [];
        configList.value.forEach(item => configValue.value[key].push(item))
      } else if (configType.value === 32) { // 汇付宝支付配置
        let key = 'productConfigs';
        configValue.value[key] = [];
        configList.value.forEach(item => configValue.value[key].push(item))
      }

      formData.value.config_value = JSON.stringify(configValue.value)
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    sysConfigSaveOrUpdate(formData.value, isCreate.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  configType.value = 0;
  configValue.value = {};
  configValue1.value = {};
  configValue2.value = {};
  configValue3.value = {};

  dynamicTags.value = [];
  configList.value = [];
  configList1.value = [];
  configList2.value = [];
  configList3.value = [];
  configList4.value = [];

  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

const initDynamicTags = (config: any[]) => {
  dynamicTags.value = [];
  config.forEach((item, index) => dynamicTags.value.push({id: 0, item: item, order_num: index}));
};
const initConfigList = (config: any[]) => {
  configList.value = [];
  config.forEach(item => configList.value.push(item));
};
const initConfigList1 = (config: any[]) => {
  configList1.value = [];
  config.forEach(item => configList1.value.push(item));
};
const initConfigList2 = (config: any[]) => {
  configList2.value = [];
  config.forEach(item => configList2.value.push(item));
};
const initConfigList3 = (config: any[]) => {
  configList3.value = [];
  config.forEach(item => configList3.value.push(item));
};
const initConfigList4 = (config: any[]) => {
  configList4.value = [];
  config.forEach(item => configList4.value.push(item));
};
</script>

<style lang="scss" scoped>
:deep(.data-form) {
  .el-input-number {
    max-width: 10rem !important;
  }
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-divider--horizontal) {
  margin: 24px 0;
}
</style>
